<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use EasyWeChat\Factory;
use think\Session;
use app\admin\model\Pep as Peps;

class Pep extends Frontend
{

    protected $model = '';
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $config = [
        'app_id' => 'wx1f8725eef4e232a4',
        'secret' => '422171ef36ac1a93c055d0191cdfb751',
        'oauth' => [
            'scopes'   => ['snsapi_userinfo'],
            'callback' => '/index/Pep/oauth',
        ]
    ];
    public $app;

    public function _initialize()
    {
        parent::_initialize();
        $this->app = Factory::officialAccount($this->config);
        $this->model = new Peps();
    }

    public function oauth()
    {
        $oauth = $this->app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        $_SESSION['wechat_user'] = $user->toArray();
        Session::set('wechat_user',$user->toArray());
        $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];

        header('location:'. $targetUrl); // 跳转到 user/profile
        return $response = $this->app->oauth->scopes(['snsapi_userinfo'])
            ->redirect();
    }

    public function index()
    {
        $oauth = $this->app->oauth;
        // 未登录
        if (empty($_SESSION['wechat_user'])) {

            $_SESSION['target_url'] = '/index/Pep/index';
//            return $oauth->redirect();
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
             $oauth->redirect()->send();
        }
        // 已经登录过
        $user = $_SESSION['wechat_user'];
        $this->app->jssdk->setUrl('');
        $jssdk = $this->app->jssdk->buildConfig(['chooseWXPay'], $debug = false, $beta = false, $json = true);
        $this->view->assign('jssdk',$jssdk);
        $row = $this->model->where(['openid'=>$user['id']])->where('pay','=',0)->find();
        if(!$row){
            return $this->view->fetch('pep/index');
        }
        if($row['pay'] == 1)
        {
            return $this->redirect('http://tmall.fc62.com/sxlq_success.html');
        }
        if($row['pay'] == 0)
        {
            $this->view->assign('row',$row);
            return $this->view->fetch('pep/edit');
        }
        return $this->view->fetch();
    }


}
